package com.skstudio.nuprint.lpd;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import com.skstudio.nuprint.LpdService;


public class LpdCommand {
	BufferedReader mReader = null;
	OutputStreamWriter mWriter = null;
	
	public LpdCommand(Socket client) throws IOException {
		mReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
		mWriter = new OutputStreamWriter(client.getOutputStream());
	}
	
	public void process() throws Exception {
		byte[] command = readCommand();
		LpdService.writeCommand(command);
		
		CommandHandler handler = null;
		switch(command[0]){
			case 0x01:
				handler = new CommandPrintJob(mReader, mWriter);
				break;
			case 0x02:
				handler = new CommandReceiveJob(mReader, mWriter);
				handler.acknowledge(GOOD_ACK);
				break;
			case 0x03:
				handler = new CommandReportQueueStateShort(mReader, mWriter);
				break;
			case 0x04:
				handler = new CommandReportQueueStateLong(mReader, mWriter);
				break;
			case 0x05:
				handler = new CommandRemovePrintJob(mReader, mWriter);
				break;
			default:
				return;
		}
		
		handler.execute(command);
	}
	
	protected byte[] readCommand() throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		do {
			int data = mReader.read();
			if (data == -1) break;
			
			baos.write(data);
			if (data == 10) break;  //LineFeed signals the end of a command
		} while(true);

		return baos.toByteArray();
	}
	
	/// <summary>
	/// Good acknowledge value defined by the RFC1179
	/// </summary>
	public static char GOOD_ACK = '\0';

	/// <summary>
	/// Bad acknowledge value defined by the RFC1179
	/// </summary>
	public static char BAD_ACK = '\1';
}
